package com.zkingsoft.actions.admin.bus;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.zkingsoft.constraint.BaseController;
import com.zkingsoft.pojo.AjaxResult;
import com.zkingsoft.util.ImageUtil;
import com.zkingsoft.util.uploadFile.UploadResult;
import com.zkingsoft.util.uploadFile.UploadUtils;

/**
 * This field was generated by Zking.software.Codegen.
 * 
 * @date 2016-11-28 15:14
 */
@Controller
@RequestMapping(value = "admin/uploadFile")
public class FileUploadController extends BaseController {
	Logger log = Logger.getLogger(FileUploadController.class);

	@Value("${file_storage_path}")
	private String fileStoragePath;
	@Value("${nginx_url}")
	private String nginxUrl;
	Properties fileUploadPro = null;

	@RequestMapping(value = "/doUpload")
	public void doFileUpload(HttpServletResponse response, MultipartHttpServletRequest request)
			throws IOException, FileUploadException {

		response.setContentType("text/html; charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		PrintWriter out = response.getWriter();
		String flag = request.getParameter("flag");
		String hiddenImg = request.getParameter("hiddenId");
		// 回调函数
		String callBack = request.getParameter("callBack");
		if (callBack != null) {
			callBack = callBack + "();";
		}
		UploadUtils uploadUtils = new UploadUtils(fileStoragePath, nginxUrl);
		UploadResult result = uploadUtils.uploadFile(request);
		if (UploadResult.STATUS_OK.equals(result.getStatus())) {
			out.print("<script type='text/javascript'>" + "		window.parent.document.getElementById('" + flag
					+ "').setAttribute('src', '" + result.getUrl() + "');"
					+ "		window.parent.document.getElementById('" + hiddenImg + "').value='" + result.getUrl() + "';"
					+ callBack + "</script>");
		} else {
			out.print("<script type='text/javascript'>" + "		window.parent.alert('" + result.info + "');"
					+ "</script>");
		}

	}

	/**
	 * 图片转换base64-png
	 */
	@RequestMapping(value = "/base64Image2Png")
	public @ResponseBody AjaxResult base64Image2Png(String base64Image) {
		// 判断文件是否存在
		String url = ImageUtil.base64Image2Png(base64Image, fileStoragePath, nginxUrl);
		log.info(url);
		AjaxResult result = new AjaxResult(AjaxResult.STATUS_OK, null, url);
		return result;
	}

}